package com.gzbsoft.sc.common.config;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.HashMap;
import java.util.Map;
@org.springframework.context.annotation.Configuration
@Data
@NoArgsConstructor
@ConfigurationProperties(prefix = "qiniu")
public class QiNiuConfig {
    private String accessKey;  //七牛的AccessKey
    private String secretKey;  //七牛的secretKey
    private String bucketImage;
    private String bucketVideo;
    private String callback;
    public String getClientTokenQiNiu(String bucket, String key) {
        StringMap stringMap = new StringMap();
        stringMap.put("persistentOps", "vframe/jpg/offset/1|saveas/" + bucket);
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucket, key, 3600000, stringMap);
    }
    public String getImgClientTokenQiNiu(String key) {
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(this.bucketImage, key);
    }
    public UploadManager getUploadManger() {
        Configuration cfg = new Configuration(Zone.autoZone());//Zone选上传地址
        return new UploadManager(cfg);
    }
    public UploadManager getVideoUploadManager() {
        Configuration cfg = new Configuration(Zone.autoZone());//Zone选上传地址
        return new UploadManager(cfg);
    }
    //生成上传视频的token
    public String getVideoTokenQiNiu(String key) {
        Auth auth = Auth.create(accessKey, secretKey);
        StringMap putPolicy = new StringMap();
        Map<String, String> callbackBody = new HashMap<>();
        //这个是上传成功会调数据,可初步数据处理
//            putPolicy.put("callbackUrl", "");
        //callback可设置key-value键值对，在上传成功会一并回掉到服务器
//            callbackBody.put("key", "value");
        //配置截取视频以及视频截取的存放路径
        String saveJpgEntry = null;
        saveJpgEntry = String.format("%s:" + key + ".jpg", this.bucketVideo);
        String vframeJpgFop = String.format("vframe/jpg/offset/1|saveas/%s", UrlSafeBase64.encodeToString(saveJpgEntry));
        //设置图片截取成功的回掉地址 公网访问
        putPolicy.put("persistentNotifyUrl", "http://gzbsc.com/jx/app/common/video/qiNiuCallBack");
//        putPolicy.put("persistentNotifyUrl", "http://gzbsc.com:9000/jx/app/common/video/qiNiuCallBack");
        //在七牛上开任务
        putPolicy.put("persistentPipeline", "CUT-Image");
        putPolicy.put("persistentOps", vframeJpgFop);
        long expireSeconds = 3600;
        //数据处理指令，支持多个指令
        putPolicy.put("callbackBodyType", "application/json");
        putPolicy.put("callbackBody", new Gson().toJson(callbackBody));
        return auth.uploadToken(this.bucketVideo, key, expireSeconds, putPolicy);
    }
}
